package com.studay;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.studay.bean.CheckResult;
import com.studay.bean.Const;
import com.util.EducationUtil;
import com.util.LogManager;
import com.xml.PaseXml;

/**
 * Login
 * 
 * @author LiuY
 */

public class LogingActivity extends Activity implements Runnable {
	private Handler handler;
	private TextView showMsgTextView;
	private TextView sbNum;
	public int count = 0;
	private AlertDialog.Builder builder;
	private Properties properties = null;
	private String mac;

	/* show alert */
	public void showAlert(String msg, final int i) {
		builder.setTitle("系统提示");
		builder.setIcon(android.R.drawable.ic_menu_myplaces);
		builder.setMessage(msg);
		builder.setCancelable(false);
		builder.setPositiveButton("退出程序",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						LogingActivity.this.finish();
						handler.removeMessages(0);
					}
				});
		// response no event
		builder.setNegativeButton("重试", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				count = i;
				LogingActivity.this.run();
			}
		});
		builder.show();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		builder = new AlertDialog.Builder(this);

		View view = findViewById(R.id.titleLayout);
		view.getBackground().setAlpha(120);

		showMsgTextView = (TextView) findViewById(R.id.showMsgTextView);
		showMsgTextView.getBackground().setAlpha(180);
		showMsgTextView.setText("正在连接服务器");

		sbNum = (TextView) findViewById(R.id.sbNum);

		handler = new Handler();
		handler.postDelayed(this, 2000);

	}

	@Override
	public void run() {
		switch (count) {
		case 0:
			showMsgTextView.setText("读取网络连接状态");
			LogManager.LogShow(Const.TAG, "读取网络连接状态", LogManager.INFO);
			/* read Internet state */
			ConnectivityManager conManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
			if (null == networkInfo) {
				// showAlert("联网失败，请检查网络", 0);
				builder.setTitle("没有可用的网络");
				builder.setMessage("请开启GPRS或WIFI网络连接");
				builder.setIcon(17301543);
				builder.setNegativeButton("退出程序",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								LogingActivity.this.finish();
								handler.removeMessages(0);
							}
						});
				builder.setPositiveButton("网络设置", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						startActivity(new Intent("android.settings.WIRELESS_SETTINGS"));
					}
				});
				builder.show();
			} else {
				handler.postDelayed(this, 1000);
				count++;
			}
			break;
		case 1:
			showMsgTextView.setText("读取设备识别码");
			/* get mac address */
			mac = Secure.getString(getApplication().getContentResolver(),
					Secure.ANDROID_ID);
			handler.postDelayed(this, 1000);
			count++;
			break;
		case 2:
			Log.i(Const.TAG, "读取身份信息");
			properties = EducationUtil.getProperties(getApplicationContext());
			if (null != properties
					&& null != properties.getProperty("keyValue")) {
				try {
					mac = EducationUtil.getMAC(
							properties.getProperty("keyValue"), mac);
					sbNum.setText("设备编码：" + mac);
					Log.i(Const.TAG,
							EducationUtil.getCheckUserUrl(properties, mac));
					URL url = new URL(EducationUtil.getCheckUserUrl(properties,
							mac));
					InputStream in = url.openConnection().getInputStream();

					CheckResult result = PaseXml.pase(in);
					if (result.getAuthFlag().equals("true")) {
						Const.result = result;
						properties.put("authFlag", result.getAuthFlag());
						properties.put("authMsg", result.getAuthMsg());
						properties.put("oraname", result.getOraname());
						properties.put("groupno", result.getGroup());
						handler.postDelayed(this, 1000);
						count++;
					} else {
						showAlert(result.getAuthMsg(), 2);
					}
				} catch (MalformedURLException e) {
					Log.e(Const.TAG, e.getMessage());
				} catch (IOException e) {
					Log.e(Const.TAG, e.getMessage());
				}
			} else {
				showAlert("身份验证失败,请联系供应商.", 2);
			}
			break;
		default:
			Log.d(Const.TAG, "进入系统");
			try {
				FileOutputStream out = new FileOutputStream(
						"/data/data/identify.conf");
				properties.store(out, "update properties");
				out.flush();
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			count = 0;
			showMsgTextView.setText("进入系统，请稍候");
			Intent intent = new Intent();
			Bundle bundle = new Bundle();
			bundle.putString("ChannelUrl",
					EducationUtil.getChannelUrl(properties));
			intent.setClass(getApplicationContext(), IndexActivity.class);
			intent.putExtras(bundle);
			LogingActivity.this.finish();
			startActivity(intent);
		}
	}
}